<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/2
 * Time: 9:47
 */

/**
 * 获取特定分组的系统配置项
 * @param $groupId 分组id
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function system_config_items($groupId)
{
    $result = \think\Db::name('system')
        ->field('cfg_name, cfg_info, cfg_value, type, sort, more')
        ->where('group', $groupId)
        ->order('sort asc')
        ->select();
    return $result;
}

/**
 * 更新配置文件
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function update_config()
{
    $str     = "<?php\n";
    $str    .= "return [\n";
    $str2    = "<?php\n";
    $str2   .= "return [\n";
    $list   = \think\Db::name('system')
        ->field('cfg_name, cfg_value, special_group')
        ->order('sort asc')
        ->select();
    foreach ($list as $key => $value) {
        if ($value['special_group'])
        {
            $str2 .= "'{$value['cfg_name']}' => \"".html_entity_decode($value['cfg_value'])."\",\n";
        } else {
            $str  .= "'{$value['cfg_name']}' => \"".html_entity_decode($value['cfg_value'])."\",\n";
        }
    }
    $str   .= "];";
    $str2  .= "];";
    $url1   = CMS_ROOT.'config/config.php';
    $url2   = CMS_ROOT.'config/db.php';
    $res2   = file_put_contents($url2, $str2);
    $res1   = file_put_contents($url1, $str);
    return ($res1 && $res2) ? true : false;
}

/**
 * 格式化文件大小
 * @param $size 文件大小K
 * @return string
 */
function GetRealSize($size)
{
    $kb = 1024;          // Kilobyte
    $mb = 1024 * $kb;    // Megabyte
    $gb = 1024 * $mb;    // Gigabyte
    $tb = 1024 * $gb;    // Terabyte
    if ($size < $kb)
        return $size . 'B';
    else if ($size < $mb)
        return round($size / $kb, 2) . 'K';
    else if ($size < $gb)
        return round($size / $mb, 2) . 'M';
    else if ($size < $tb)
        return round($size / $gb, 2) . 'G';
    else
        return round($size / $tb, 2) . 'T';
}

/**
 * 获取加密的密码
 * @param $pass   密码明文
 * @return string 加密字符串
 */
function get_hash_pass($pass)
{
    $result = md5(md5($pass) . md5('woshinibaba'));
    return $result;
}

/**
 * 权限检查
 * @param $controller 控制器名
 * @param $action 操作名
 * @param $juri 权限数组
 * @return array
 */
function check_juri($controller, $action, $juri)
{
    if (!array_key_exists($controller, $juri))
    {
        return ['status'=>false, 'msg'=>'您没有该模块的权限！'];
    } else {
        if (!in_array($action, $juri[$controller]))
        {
            return ['status'=>false, 'msg'=>'您没有操作该功能的权限！'];
        }
    }
    return ['status'=>true, 'msg'=>''];
}